<template>
  <div>
    <Breadcrumb>
      <BreadcrumbItem to="/main">
         <e-icon icon-name="el-icon-s-home"></e-icon>主页 
      </BreadcrumbItem>
    </Breadcrumb>
    <Divider />

    <Card style="width: 480px; height: 200px">
      <div style="float: left; width: 130px">
        <Avatar
          style="
            color: #f56a00;
            width: 120px;
            height: 120px;
            background-color: #e3f2fd;
            text-algin: center;
            line-height: 120px;
            font-size: 26px
          "
          >{{ myInfo.name }}</Avatar
        >
      </div>
      <div style="width: 40px; height: 200px; float: left"></div>
      <div style="text-align: left">
        <h4>我的名称：{{ myInfo.name }}</h4>
        <h4>我的账号：{{ myInfo.account }}</h4>
        <h4 style="text-algin: center">
          我的角色：
          <span
            v-for="(items, index) in UserRoleMenuPo.sysRoleList"
            :key="index"
          >
            <Tag type="dot" color="primary">{{ items.name }}</Tag>
          </span>
        </h4>
      </div>

      <Button style="margin-top: 30px" type="primary" @click="open2"
        >修改密码</Button
      >
      <Button
        style="margin-top: 30px; margin-left: 50px"
        type="primary"
        @click="open"
        >修改名称</Button
      >
    </Card>

    <Modal
      ref="modal2"
      :loading="isLoading"
      v-model="modal2"
      title="修改密码"
      @on-ok="updatePsw('userPo2')"
      @on-cancel="cancel"
    >
      <Form ref="userPo2" :rules="ruleValidate2" :label-width="80">
        <FormItem label="原密码" prop="oldPsw">
          <Input
            type="password"
            password 
            clearable
            v-model="oldPsw"
            placeholder="请输入原密码"
          ></Input>
        </FormItem>
        <FormItem label="新密码" prop="newPsw">
          <Input
            type="password"
            password 
            clearable
            v-model="newPsw"
            placeholder="请输入第一遍新密码"
          ></Input>
        </FormItem>
        <FormItem label="新密码" prop="newPsw2">
          <Input
            type="password"
            password 
            clearable
            v-model="newPsw2"
            placeholder="请输入第二遍新密码"
          ></Input>
        </FormItem>
      </Form>
    </Modal>

    <Modal
      ref="modal"
      :loading="isLoading"
      v-model="modal"
      title="修改名称"
      @on-ok="updateName('userPo')"
      @on-cancel="cancel"
    >
      <Form ref="userPo" :rules="ruleValidate" :label-width="80">
        <FormItem label="用户名称" prop="name">
          <Input clearable v-model="name" placeholder="请输入用户名称"></Input>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
export default {
  data() {
    const validateOldPass = (rule, value, callback) => {
      if (this.oldPsw === "") {
        callback(new Error("请输入原密码"));
      } else {
        callback();
      }
    };
    const validateNameCheck = (rule, value, callback) => {
      if (this.name === "") {
        callback(new Error("请输入用户名称"));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      if (this.newPsw === "") {
        callback(new Error("请输入新密码"));
      } else {
        if (this.newPsw2 !== "") {
          // 对第二个密码框单独验证
          this.$refs.userPo2.validateField("newPsw2");
        }
        callback();
      }
    };
    const validatePassCheck = (rule, value, callback) => {
      if (this.newPsw2 === "") {
        callback(new Error("请再次输入新密码"));
      } else if (this.newPsw2 !== this.newPsw) {
        callback(new Error("两次密码不一致，请确认输入!"));
      } else {
        callback();
      }
    };
    return {
      //存放个人信息，通过登陆时保存到store
      myInfo: {},
      oldPsw: "",
      newPsw: "",
      newPsw2: "",
      isLoading: true,
      modal2: false,
      modal: false,
      UserRoleMenuPo: "",
      name: "",
      //修改密码时的表单验证
      ruleValidate2: {
        oldPsw: [{ validator: validateOldPass, trigger: "blur" }],
        newPsw: [
          {
            validator: validatePass,
            trigger: "blur",
          },
        ],
        newPsw2: [
          {
            validator: validatePassCheck,
            trigger: "blur",
          },
        ],
      },
      //修改用户的验证
      ruleValidate: {
        name: [
          {
            validator: validateNameCheck,
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.myInfo = this.$store.state.myInfo;
    this.$axios
      .get("/user/selectUserById", {
        params: {
          id: this.$store.state.myInfo.id,
        },
      })
      .then((result) => {
        this.UserRoleMenuPo = result.data.data;
      })
      .catch((err) => {
        console.log(err);
      });
  },
  methods: {
    //打开修改密码弹窗
    open2() {
      this.modal2 = true;
    },
    open() {
      this.modal = true;
      this.name = this.myInfo.name;
    },
    cancel() {},
    //修改密码成功退出系统
    quit() {
      this.$axios
        .get("/user/quit")
        .then((result) => {
          if (result.data.code == 0) {
            this.$store.commit("userStatus", null);
            this.$router.push("/login");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //修改密码
    updatePsw(name) {
      this.$refs[name].validate((valid) => {
        //验证输入的用户信息是否正确
        if (valid) {
          this.$axios
            .get("/user/updatePsw", {
              params: {
                id: this.$store.state.myInfo.id,
                oldPsw: this.oldPsw,
                newPsw: this.newPsw,
              },
            })
            .then((result) => {
              if (result.data.code == 0) {
                this.$Message.success({
                  duration: 4.5,
                  background: true,
                  content: "修改密码成功，将于三秒后重新登录",
                });
                //修改密码成功重新登录
                this.modal2 = false;
                var _this = this;
                setTimeout(function () {
                  _this.quit();
                }, 3000);
              } else {
                //输入原密码错误
                this.$Message.error({
                  duration: 3,
                  background: true,
                  content: result.data.msg,
                });
                this.oldPsw = "";
                setTimeout(() => {
                  this.isLoading = false;
                  this.$nextTick(() => {
                    this.isLoading = true;
                  });
                }, 100);
                return;
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
        //若验证数据错误，不关闭弹窗
        else {
          setTimeout(() => {
            this.isLoading = false;
            this.$nextTick(() => {
              this.isLoading = true;
            });
          }, 100);
          return;
        }
      });
    },
    //修改用户名
    updateName(name) {
      this.$refs[name].validate((valid) => {
        //验证输入的用户信息是否正确
        if (valid) {
          this.$axios
            .get("/user/updateName", {
              params: {
                id: this.$store.state.myInfo.id,
                name: this.name,
              },
            })
            .then((result) => {
              if (result.data.code == 0) {
                this.$Message.success({
                  duration: 4.5,
                  background: true,
                  content: "修改用户名成功",
                });
                //将用户名放入sessionStorage
                sessionStorage.setItem(
                  "userInfo",
                  JSON.stringify(result.data.data)
                );
                this.modal = false;
                this.myInfo.name = this.name;
              } else {
                this.$Message.error({
                  duration: 3,
                  background: true,
                  content: result.data.msg,
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
        //若验证数据错误，不关闭弹窗
        else {
          setTimeout(() => {
            this.isLoading = false;
            this.$nextTick(() => {
              this.isLoading = true;
            });
          }, 100);
          return;
        }
      });
    },
  },
};
</script>

<style>
</style>